//
//  FlutterMicImpl.swift
//  Runner
//
//  Created by 莫华军 on 2024/9/21.
//

import Foundation
import AVFoundation
import MediaPlayer
import Flutter

class FlutterMicImpl: FlutterAppDelegate, AudioSpectrumPlayerDelegate{
    
    func player(_ player: AudioSpectrumPlayer, didGenerateSpectrum spectra: [[Float]]) {
        let progress = Int(player.getCurrentPosition()*1000)
        var max:Float = 0.0
        for i in 0..<128 {
            if(max < spectra[0][i]){
                max = spectra[0][i]
            }
        }
        
        var s:Float = 0;
        if(max == 0){
            
        }else{
            s = 127/max
            if(s>10000){
                s = 10000
            }
        }
        
        var list:[Int] = []
        for i in 0..<128 {
            list.append(Int(spectra[0][i]*s))
        }
        
        //print("progress:\(progress)")
        
        
        
        DispatchQueue.main.async {
            self.musicMethodChannel?.invokeMethod("onProgress", arguments: progress)
            self.musicMethodChannel?.invokeMethod("onFftDataCapture", arguments: list)
        }
    }
    
    static let sharedInstance = FlutterMicImpl()
    private var micMethodChannel: FlutterMethodChannel?
    private var musicMethodChannel: FlutterMethodChannel?
    var player: AudioSpectrumPlayer!
    private var recordTool: RecordTool?
    private  override init() {
        
    }
    
    func setFlutterBinaryMessenger(binaryMessenger:FlutterBinaryMessenger){
        ///麦克风数据
        micMethodChannel = FlutterMethodChannel(name: "mic_method_channel", binaryMessenger: binaryMessenger)
        micMethodChannel?.setMethodCallHandler { (call:FlutterMethodCall, result:@escaping FlutterResult) in
            
            if (call.method == "startRecord") {
                if(self.recordTool == nil){
                    self.recordTool = RecordTool()
                }
                self.recordTool?.startRecording(realTime: { data in
                    //print(data)
                    self.micMethodChannel?.invokeMethod("onMicData", arguments: ["data":data])
                })
            }else if (call.method == "stopRecord"){
                self.recordTool?.stopRecording()
                self.recordTool = nil;
                self.player = AudioSpectrumPlayer()
                self.player.delegate = self
            }
            
        }
        
        //音乐播放
        player = AudioSpectrumPlayer()
        player.delegate = self
        musicMethodChannel = FlutterMethodChannel(name: "lib_music", binaryMessenger: binaryMessenger)
        musicMethodChannel?.setMethodCallHandler { (call:FlutterMethodCall, result:@escaping FlutterResult) in
            
            if (call.method == "getMusicList") {
                let mediaQueue = MPMediaQuery.songs()
                var trackPaths = mediaQueue.items ?? []
                
                var list  = []
                for item in trackPaths {
                    //print("name:\(item.title ?? "") url:\(item.assetURL?.absoluteString ?? "")")
                    
                    let duration = item.value(forProperty: MPMediaItemPropertyPlaybackDuration) as? TimeInterval
                    let d:Int = Int((duration ?? 0)*1000);
                    list.append(["title":item.title,"artist":item.artist,"duration":d,"url":item.assetURL?.absoluteString])
                }
                result(list)
            }else if(call.method == "startPlay"){
                if let args = call.arguments as? [String: Any]{
                    var url:String = args["uri"] as! String
                    self.player?.play(withFileName:  URL(string: url))
                    self.musicMethodChannel?.invokeMethod("onStartPlay", arguments: "")
                }
            }else if(call.method == "stopPlay"){
                self.player?.stop()
                //self.musicMethodChannel?.invokeMethod("onPlayComplete", arguments: "")
            }else if(call.method == "pausePlay"){
                self.player?.pause()
                self.musicMethodChannel?.invokeMethod("onPausePlay", arguments: "")
            }else if(call.method == "continuePlay"){
                self.player?.continuePlay()
                self.musicMethodChannel?.invokeMethod("onStartPlay", arguments: "")
            }else if(call.method == "seekTo"){
                if let args = call.arguments as? [String: Any]{
                    var progress:Int = args["progress"] as! Int
                    self.player?.seekTo(time: Float(progress/1000))
                    self.musicMethodChannel?.invokeMethod("onStartPlay", arguments: "")
                }
            }else if(call.method == "setVolume"){
                if let args = call.arguments as? [String: Any]{
                    var volume:Int = args["volume"] as! Int
                    print("设置音量\(volume)")
                    self.player?.setVolume(volume: Float(volume)/100)
                }
            }
        }
    }
}
